package com.xb.service.imp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xb.entity.*;
import com.xb.mapper.*;
import com.xb.service.IPatientService;
import com.xb.util.IDCardUtil;
import com.xb.util.Result;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Service业务层处理
 */
@Service
public class PatientServiceImp implements IPatientService {
    @Resource
    private PatientMapper patientMapper;
    @Resource
    private IdcardMapper idcardMapper;
    @Resource
    private RegisterMapper registerMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private TollTakeDrugMapper tollTakeDrugMapper;
    @Resource
    private MedicalRecordMapper recordMapper;


    @Override
    public Patient selectPatientByIdCard(String idCard) {
        return patientMapper.selectPatientByIdCard(idCard);
    }

    @Transactional
    @Override
    public Result selectPatientByPatient(GetCardIdInfoReqVO getCardIdInfoReqVO, HttpSession session) {
        Result result = new Result();
        String email = (String) session.getAttribute("email");
        User user = userMapper.selectUserByEmail(email);
        int cardId = getCardIdInfoReqVO.getCardId();
        Register register = new Register();
        register.setPatientId(cardId);
        register.setDoctorId(user.getId());
        Register reg = registerMapper.selectRegister(register);
        if (reg == null) {
            result.setStatus(Result.RESPONSE_FAIL);
            result.setMessage("没有该患者信息！");
        } else {
            if (recordMapper.selectMedicalRecordByRegisterId(reg.getId()) == null) {
                TollTakeDrug tollTakeDrug = new TollTakeDrug();
                tollTakeDrug.setPrescriptionNum("O" + System.currentTimeMillis());
                tollTakeDrug.setTakingDrugStatus(-1);
                tollTakeDrug.setPatientId(getCardIdInfoReqVO.getCardId());
                tollTakeDrugMapper.insertTollTakeDrug(tollTakeDrug);
                MedicalRecord medicalRecord = new MedicalRecord();
                medicalRecord.setPrescriptionNum(tollTakeDrug.getPrescriptionNum());
                medicalRecord.setRegisterId(reg.getId());
                recordMapper.insertMedicalRecord(medicalRecord);
            }
            Patient patient = patientMapper.selectPatientByRegister(register);
            System.out.println(patient);
            result.setStatus(Result.RESPONSE_SUCCESS);
            if (patient != null) {
                result.setData(patient);
            } else {
                result.setStatus(Result.RESPONSE_FAIL);
                result.setMessage("没有此就诊卡信息！");
            }
        }
        return result;
    }

    @Override
    public Result medicalRecordGetCardIdInfo(GetCardIdInfoReqVO getCardIdInfoReqVO, HttpSession session) {
        Result result = new Result();
        String email = (String) session.getAttribute("email");
        User user = userMapper.selectUserByEmail(email);
        int cardId = getCardIdInfoReqVO.getCardId();
        Register register = new Register();
        register.setPatientId(cardId);
        register.setDoctorId(user.getId());
        Register reg = registerMapper.selectRegister(register);
        if (reg == null) {
            result.setStatus(Result.RESPONSE_FAIL);
            result.setMessage("没有该患者信息！");
        } else {

            if (recordMapper.checkMedicalRecordGetCardIdInfo(cardId) == null) {
                TollTakeDrug tollTakeDrug = new TollTakeDrug();
                tollTakeDrug.setPrescriptionNum("O" + System.currentTimeMillis());
                tollTakeDrug.setTakingDrugStatus(-1);
                tollTakeDrug.setPatientId(getCardIdInfoReqVO.getCardId());
                tollTakeDrugMapper.insertTollTakeDrug(tollTakeDrug);
                MedicalRecord medicalRecord = new MedicalRecord();
                medicalRecord.setPrescriptionNum(tollTakeDrug.getPrescriptionNum());
                medicalRecord.setRegisterId(reg.getId());
                recordMapper.insertMedicalRecord(medicalRecord);
            }
            Patient patient = patientMapper.selectPatientByCardId(getCardIdInfoReqVO.getCardId());
            result.setStatus(Result.RESPONSE_SUCCESS);
            if (patient != null) {
                result.setData(patient);
            } else {
                result.setStatus(Result.RESPONSE_FAIL);
                result.setMessage("没有此就诊卡信息！");
            }
        }
        return result;
    }

    @Override
    public Patient selectPatientByRegisterId(int registerId) {
        return patientMapper.selectPatientByRegisterId(registerId);
    }

    @Override
    public Patient checkPatient(int cardId) {
        return patientMapper.checkPatient(cardId);
    }

    @Override
    public Result getExaminationToll(int cardId) {
        Result result = new Result();
        try {
            ExaminationToll examinationToll = patientMapper.getExaminationToll(cardId);

            if (examinationToll != null) {
                result.setStatus(Result.RESPONSE_SUCCESS);
                result.setData(examinationToll);
            } else {
                result.setStatus(Result.RESPONSE_FAIL);
                result.setMessage("没有找到该患者信息！");
            }
            return result;
        } catch (TooManyResultsException e) {
            e.printStackTrace();
            result.setMessage("该患者有多条未付款信息！");
            return result;
        }

    }

    /**
     * 分页查询列表
     *
     * @param patient
     * @return
     */
    @Override
    public Result selectPatientList(Patient patient, Integer page, Integer limit) {
        Result result = new Result();
        PageHelper.startPage(page, limit);
        List<Patient> list = patientMapper.selectPatientList(patient);
        PageInfo<Patient> patientPageInfo = new PageInfo<>(list);
        if (patientPageInfo.getList() != null) {
            result.setStatus(Result.RESPONSE_SUCCESS);
            result.setData(patientPageInfo.getList());
            result.setTotal(patientPageInfo.getTotal());
            result.setMessage("查询成功");
        }
        return result;
    }

    /**
     * 新增
     *
     * @param patient
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean insertPatient(Patient patient) {
        try {
            if (idcardMapper.selectIdcardByIdCard(patient.getIdCard()) != null || patientMapper.selectPatientByIdCard(patient.getIdCard()) != null) {
                throw new IllegalAccessException("已有该身份证");
            }
            Idcard idcard = new Idcard();
            idcard.setName(patient.getName());
            idcard.setAddress(patient.getAddress());
            idcard.setBirthday(patient.getBirthday());
            idcard.setSex(patient.getSex());
            idcard.setNationality(patient.getNationality());
            idcard.setIdCard(patient.getIdCard());
            idcardMapper.insertIdcard(idcard);
            patient.setCardId(String.valueOf(idcard.getId()));
            patientMapper.insertPatient(patient);

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean reissuePatient(Patient patient) {
        try {
            Idcard idcard = idcardMapper.selectIdcardByIdCard(patient.getIdCard());
            patient.setCardId(String.valueOf(idcard.getId()));
            patient.setAge(Integer.valueOf(IDCardUtil.getAge(patient.getIdCard())));
            patient.setBirthday(IDCardUtil.getBirthday(patient.getIdCard()));
            patient.setSex(IDCardUtil.getSex(patient.getIdCard()));
            if (patientMapper.insertPatient(patient) == 0) {
                throw new IllegalAccessException("Patient添加失败！");
            }
            idcard.setName(patient.getName());
            idcard.setNationality(patient.getNationality());
            idcard.setAddress(patient.getAddress());
            if (idcardMapper.updateIdcard(idcard) == 0) {
                throw new IllegalAccessException("IdCard修改失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }

        return true;
    }

    /**
     * 修改
     *
     * @param patient
     * @return 结果
     */
    @Override
    public boolean updatePatientByCardId(Patient patient) {
        return patientMapper.updatePatientByCardId(patient) > 0;
    }

    @Transactional
    @Override
    public Result update(Patient obj) {
        Result result = new Result();
        try {
            if (!IDCardUtil.validateCard(obj.getIdCard())) {
                throw new IllegalAccessException("身份证不合规！");
            }
            if (idcardMapper.selectIdcardByIdCard(obj.getIdCard()) != null) {
                if (!idcardMapper.selectIdcardByIdCard(obj.getIdCard()).getIdCard().equals(obj.getIdCard())) {
                    throw new IllegalAccessException("已有该身份证");
                }
            }

            Idcard idcard = new Idcard();
            obj.setSex(IDCardUtil.getSex(obj.getIdCard()));
            obj.setAge(Integer.valueOf(IDCardUtil.getAge(obj.getIdCard())));
            obj.setBirthday(IDCardUtil.getBirthday(obj.getIdCard()));
            if (patientMapper.updatePatientByCardId(obj) == 0) {
                throw new IllegalAccessException("修改失败！");
            }
            idcard.setName(obj.getName());
            idcard.setAddress(obj.getAddress());
            idcard.setBirthday(obj.getBirthday());
            idcard.setSex(obj.getSex());
            idcard.setNationality(obj.getNationality());
            idcard.setIdCard(obj.getIdCard());
            idcard.setId(Integer.valueOf(obj.getCardId()));
            if (idcardMapper.updateIdcard(idcard) == 0) {
                throw new IllegalAccessException("修改失败！");
            }

            result.setStatus(Result.RESPONSE_SUCCESS);
            result.setMessage("修改成功！");
            return result;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.setMessage(e.getMessage());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.setMessage("ERROR:请联系管理员");
            return result;
        }
    }

    @Transactional
    @Override
    public Result add(Patient obj) {
        Result result = new Result();
        try {
            if (idcardMapper.selectIdcardByIdCard(obj.getIdCard()) != null && patientMapper.selectPatientByIdCard(obj.getIdCard()) != null) {
                throw new IllegalAccessException("已有该身份证");
            }
            if (!IDCardUtil.validateCard(obj.getIdCard())) {
                throw new IllegalAccessException("身份证不合规！");
            }
            Idcard idcard = new Idcard();
            obj.setSex(IDCardUtil.getSex(obj.getIdCard()));
            obj.setAge(Integer.valueOf(IDCardUtil.getAge(obj.getIdCard())));
            obj.setBirthday(IDCardUtil.getBirthday(obj.getIdCard()));
            if (idcardMapper.selectIdcardByIdCard(obj.getIdCard()) == null) {
                idcard.setName(obj.getName());
                idcard.setAddress(obj.getAddress());
                idcard.setBirthday(obj.getBirthday());
                idcard.setSex(obj.getSex());
                idcard.setNationality(obj.getNationality());
                idcard.setIdCard(obj.getIdCard());
                if (idcardMapper.insertIdcard(idcard) == 0) {
                    throw new IllegalAccessException("添加失败！");
                }
                if (patientMapper.selectPatientByIdCard(obj.getIdCard()) != null) {
                    if (patientMapper.deletePatientByIdCard(obj.getIdCard()) == 0) {
                        throw new IllegalAccessException("添加失败！");
                    }
                }
                obj.setCardId(String.valueOf(idcard.getId()));
            } else {
                idcard.setId(idcardMapper.selectIdcardByIdCard(obj.getIdCard()).getId());
                obj.setCardId(String.valueOf(idcard.getId()));
            }
            if (patientMapper.insertPatient(obj) == 0) {
                throw new IllegalAccessException("添加失败！");
            }
            result.setStatus(Result.RESPONSE_SUCCESS);
            result.setMessage("添加成功！");
            return result;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.setMessage(e.getMessage());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.setMessage("ERROR:请联系管理员");
            return result;
        }
    }
}
